#include <ncurses.h>
#include <string>

#include "Curses.h"
#include "PickupPrompt.h"

const int maxItems = 15;

PickupPrompt::PickupPrompt(std::vector<Item *> items)
 : Window(25, 3 + (items.size() < maxItems ? items.size() : maxItems), 2, 2, true), m_items(items)
{
	
}

std::vector<Item *> PickupPrompt::show() {
	std::vector<Item *> result;
	Curses curses = Curses::instance();

	
	result = singleWindow();
		
	
	curses.clearScreen();
	curses.refresh();
	
	return result;
}

std::vector<Item *> PickupPrompt::singleWindow() {
	std::vector<Item *> result;
	Curses curses = Curses::instance();

	curses.pushWindow(this);

	std::vector<bool> selectVector;
	for (size_t i = 0; i < m_items.size(); i++)
		selectVector.push_back(false);

	int key = 0;
	int page = 1;

	while (key != '\n') {

		curses.print(this, 1, height() - 2, "Space - Next page");
		for (size_t i = 0; i < maxItems; i++) {
			if (i + (page - 1) * maxItems < m_items.size()) {
				std::string str = std::string(" - ") + m_items[i + (page - 1) * maxItems]->name();
				curses.putchar(this, 1, 1 + i, 'a' + i);
				if (selectVector[i + (page - 1) * maxItems])
					str[1] = '+';
				curses.print(this, 2, 1 + i, str);
			}
		}
	
		curses.refresh();
		
		key = curses.getchar();
		
		if (key >= 'a' && key <= 'z') {
			key -= 'a';
			if (key + (page - 1) * maxItems < m_items.size()) {
				selectVector[key + (page - 1) * maxItems] = !selectVector[key + (page - 1) * maxItems];
			}
		}
		
		// Pick up all items on page.
		if (key == ',') {
			for (int i = 0; i < maxItems; i++) {
				if (i + (page - 1) * maxItems < m_items.size()) {
					selectVector[i + (page - 1) * maxItems] = !selectVector[i + (page - 1) * maxItems];
				}
			}
		}
		
		if (key == ' ') {
			if (m_items.size() <= page * maxItems)
				break;
			else {
				page++;
				clear();
			}
		}
		
	}

	curses.popWindow();

	for (size_t i = 0; i < m_items.size(); i++) {
		if (selectVector[i]) {
			result.push_back(m_items[i]);
		}
	}

	
	return result;
}
